package com.comleader.operator.core.handler;

import java.lang.reflect.Type;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import com.comleader.operator.common.response.Result;

import cn.hutool.json.JSONUtil;
import sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl;

/**
 * @Description
 * @Auhtor 连新景
 * @Date 2024/07/10 15:08
 */
@RestControllerAdvice(basePackages = {"com.comleader.operator.controller"}) // 注意哦，这里要加上需要扫描的包
public class ResponseControllerHandler implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> aClass) {
        Type parameterType = returnType.getGenericParameterType();
        // 如果接口返回的类型本身就是Result 那就没有必要进行额外的操作，返回false
        if (parameterType.equals(Result.class) ) {
            return false;
        }
        // 如果返回对象是泛型，需要拿到rawType才行
        if (parameterType instanceof ParameterizedTypeImpl) {
            ParameterizedTypeImpl typeImpl = (ParameterizedTypeImpl)returnType.getGenericParameterType();
            return !typeImpl.getRawType().equals(Result.class);
        }
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object data, MethodParameter returnType, MediaType mediaType,
        Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest request, ServerHttpResponse response) {
        // String类型不能直接包装，所以要进行些特别的处理
        if (returnType.getGenericParameterType().equals(String.class)) {
            return JSONUtil.toJsonStr(Result.success(data));
        }
        // 将原本的数据包装在Result里
        return Result.success(data);
    }
}